<?php

namespace app\api\controller;

use app\model\zs\ZsBusiness;
use app\model\zs\ZsMemberArticle;
use app\model\zs\ZsMemberArticleComment;
use app\model\zs\ZsMemberCoupon;
use app\model\zs\ZsMemberCouponProvide;
use app\model\zs\ZsMemberLike;
use app\model\zs\ZsRewardLog;
use app\model\zs\ZsMemberMeal;
use app\model\zs\ZsMemberMedia;
use app\model\zs\ZsMemberTopic;
use app\repository\BusinessRepository;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use WeChat\Exceptions\InvalidResponseException;
use WeMini\Security;

/**
 * 小程序种草API
 * Class Article
 * @package app\api\controller
 */
class Article
{
    const PAGE_SIZE = 6;

    /**
     * 小程序配置参数
     * @var array
     */
    protected $config;

    public function __construct()
    {
        $this->config = [
            'appid'      => sysconf('data.wxapp_appid'),
            'appsecret'  => sysconf('data.wxapp_appkey'),
            'mch_id'     => sysconf('data.wxapp_mch_id'),
            'mch_key'    => sysconf('data.wxapp_mch_key'),
            'cache_path' => app()->getRuntimePath() . 'wechat',
        ];
    }

    /**
     * 种草列表
     */
    public function list()
    {
        $vipcode = Request::param('vipcode');
        $sort = Request::param('sort');                 // time-时间排序, like_num-点赞排序
        $search_val = Request::param('search_val');     // 标题/内容/商户名
        $topic_id = Request::param('topic_id');         // 话题ID

        $base_query = ZsMemberArticle::where('audit_status', ZsMemberArticle::AUDIT_STATUS_PASS)
            ->where('status', ZsMemberArticle::STATUS_ON)
            ->where(function ($query) use ($search_val, $topic_id) {
                if ($topic_id) {
                    $query->where('rel_topic_id', $topic_id);
                }
                if ($search_val) {
                    $query->where('title|content', 'like', "%{$search_val}%");
                    // 搜索商户名
                    $query->whereExists(function ($existQuery) use ($search_val) {
                        $existQuery->table('business')->whereRaw('business.id = member_articles.rel_business_id')
                            ->where('brandname', 'like', "%{$search_val}%");
                    }, 'OR');
                }

            })
            ->with('memberUser');
        switch ($sort) {
            case 'time':
                $list_article = $base_query->order('id', 'desc')->paginate(static::PAGE_SIZE);
                break;
            case 'like_num':
                $list_article = $base_query->order('like_num', 'desc')->paginate(static::PAGE_SIZE);
                break;
            default:
                $list_article = $base_query->order('id', 'desc')->paginate(static::PAGE_SIZE);
        }

        $list_media = $list_article->column('media_arr');
        $list_first_media = $this->listFirstMedia($list_media);
        $list_first_media_item = $this->listFirstMediaItem($list_first_media);

        $like_article_id_arr = $this->ilkeArticleIdArr($list_article->column('id'), $vipcode);

        $list = $list_article->map(function ($item_article) use ($list_first_media_item, $like_article_id_arr) {
            $first_media_id = $this->firstMedia($item_article->media_arr);
            $first_media_item = $list_first_media_item->where('id', $first_media_id)->first();

            $default_nickname = '神秘用户';
            $default_avatar = '/static/images/face.png';
            $user_nickname = $item_article->memberUser->nickName ?? '';
            $user_avatar = $item_article->memberUser->avatarUrl ?? '';
            $user_nickname = mb_substr($user_nickname ?: $default_nickname, 0, 8, 'utf-8');
            $user_avatar = $user_avatar ?: $default_avatar;

            $is_like = in_array($item_article->id, $like_article_id_arr);
            return [
                'article_id' => $item_article->id,
                'title' => $item_article->title,
                'user_nickname' => $user_nickname,
                'user_avatar' => $user_avatar,
                'like_num' =>$item_article->like_num,
                'headimg' => $first_media_item['url'] ?? '',

                'is_like' => $is_like,
                'like_color' => $this->likeColor($is_like),
            ];
        });

        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 我发布的种草列表
     */
    public function mylist()
    {
        $vipcode = Request::param('vipcode');
        $list_article = ZsMemberArticle::where('vipcode', $vipcode)
            ->where('status', ZsMemberArticle::STATUS_ON)
            ->with('memberUser')
            ->order('id', 'desc')
            ->paginate(static::PAGE_SIZE);

        $list_media = $list_article->column('media_arr');
        $list_first_media = $this->listFirstMedia($list_media);
        $list_first_media_item = $this->listFirstMediaItem($list_first_media);

        $list = $list_article->map(function ($item_article) use ($list_first_media_item) {
            $first_media_id = $this->firstMedia($item_article->media_arr);
            $first_media_item = $list_first_media_item->where('id', $first_media_id)->first();

            $default_nickname = '神秘用户';
            $default_avatar = '/static/images/face.png';
            $user_nickname = $item_article->memberUser->nickName ?? '';
            $user_avatar = $item_article->memberUser->avatarUrl ?? '';
            $user_nickname = mb_substr($user_nickname ?: $default_nickname, 0, 8, 'utf-8');
            $user_avatar = $user_avatar ?: $default_avatar;

            $audit_status = $item_article->audit_status;
            return [
                'article_id' => $item_article->id,
                'title' => $item_article->title,
                'user_nickname' => $user_nickname,
                'user_avatar' => $user_avatar,
                'like_num' =>$item_article->like_num,
                'headimg' => $first_media_item['url'] ?? '',

                // 增加审核状态的返回
                'audit_status_text' => ZsMemberArticle::auditStatusRelsMini()[$audit_status] ?? '',
                'audit_status_class' => ZsMemberArticle::auditStatusClassRelsMini()[$audit_status] ?? '',

                'is_like' => false,
                'like_color' => $this->likeColor(false),
            ];
        });

        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 我赞过的种草列表
     */
    public function likelist()
    {
        $vipcode = Request::param('vipcode');
        $list_like = ZsMemberLike::where('vipcode', $vipcode)
            ->where('like_status', ZsMemberLike::LIKE_STATUS_ON)
            ->with('memberArticle', 'articleUser')
            ->order('id', 'desc')
            ->paginate(static::PAGE_SIZE);

        $list_article = collect($list_like->column('memberArticle'));
        $list_media = $list_article->column('media_arr');
        $list_first_media = $this->listFirstMedia($list_media);
        $list_first_media_item = $this->listFirstMediaItem($list_first_media);

        $list = $list_like->map(function ($item_like) use ($list_first_media_item) {
            $item_article = $item_like->memberArticle;

            $first_media_id = $this->firstMedia($item_article->media_arr);
            $first_media_item = $list_first_media_item->where('id', $first_media_id)->first();

            $default_nickname = '神秘用户';
            $default_avatar = '/static/images/face.png';
            $user_nickname = $item_like->articleUser->nickName ?? '';
            $user_avatar = $item_like->articleUser->avatarUrl ?? '';
            $user_nickname = mb_substr($user_nickname ?: $default_nickname, 0, 8, 'utf-8');
            $user_avatar = $user_avatar ?: $default_avatar;
            return [
                'article_id' => $item_article->id,
                'title' => $item_article->title,
                'user_nickname' => $user_nickname,
                'user_avatar' => $user_avatar,
                'like_num' =>$item_article->like_num,
                'headimg' => $first_media_item['url'] ?? '',

                'is_like' => true,
                'like_color' => $this->likeColor(true),
            ];
        });

        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 种草详情页
     */
    public function detail()
    {
        $article_id = Request::param('article_id');
        $vipcode = Request::param('vipcode');

        $model_article = $this->getArticle($article_id);
        if (!$model_article) {
            return jsonData(0, '种草不存在');
        }
        // 文章 status 非正常
        if (!$this->isArticleStatusOn($model_article->status)) {
            return jsonData(0, '无法查看[0x01]');
        }
        // 当前不是自己的种草，并且不是审核通过状态
        $is_self = $model_article->vipcode === $vipcode;
        if (!$is_self && !$this->isAuditPass($model_article->audit_status)) {
            return jsonData(0, '无法查看[0x02]');
        }

        $list_media = $this->listFirstMediaItem($model_article->media_arr);

        $like_article_id_arr = $this->ilkeArticleIdArr([$article_id], $vipcode);
        $is_like = in_array($article_id, $like_article_id_arr);

        $default_nickname = '神秘用户';
        $default_avatar = '/static/images/face.png';
        $user_nickname = $model_article->memberUser->nickName ?? '';
        $user_avatar = $model_article->memberUser->avatarUrl ?? '';
        $user_nickname = mb_substr($user_nickname ?: $default_nickname, 0, 8, 'utf-8');
        $user_avatar = $user_avatar ?: $default_avatar;

        $businessRepository = app(BusinessRepository::class);
        $store_floor_new = $model_article->relBusiness->floor_new ?? '';
        $store_floor_text = $store_floor_new ? $businessRepository->floorText($store_floor_new) : '';

        $topic_text = $model_article->relTopic->name ?? '';
        $topic_text = $topic_text ? $this->joinTopicText($topic_text) : '';

        $coupon_b_amount = $model_article->relCoupon->b_amount ?? '';
        $coupon_t_amount = $model_article->relCoupon->t_amount ?? '';
        $coupon_b_amount = is_numeric($coupon_b_amount) ? "￥{$coupon_b_amount}" : '';
        $coupon_t_amount = is_numeric($coupon_t_amount) ? "￥{$coupon_t_amount}" : '';
        // 返回数组
        $data = [
            'article_id' => $model_article->id,
            'title' => $model_article->title,
            'content' => $model_article->content,
            'user_nickname' => $user_nickname,
            'user_avatar' => $user_avatar,
            'like_num' => $model_article->like_num,
            'media_arr_url' => $this->joinSwiper($list_media, $model_article->media_arr),

            // 关联话题、商户、优惠券数据
            'topic_id' => $model_article->rel_topic_id,
            'topic_text' => $topic_text,
            'coupon_id' => $model_article->rel_coupon_tid,
            'coupon_id_raw' => $model_article->relCoupon->id ?? '',
            'coupon_text' => $model_article->relCoupon->tname ?? '',
            'coupon_img' => $model_article->relCoupon->img ?? '',
            'coupon_b_amount' => $coupon_b_amount,
            'coupon_t_amount' => $coupon_t_amount,
            'store_id' => $model_article->rel_business_id,
            'store_text' => $model_article->relBusiness->brandname ?? '',
            'store_floor_text' => $store_floor_text,
            'store_img' => $model_article->relBusiness->headimg ?? '',

            'is_like' => $is_like,
            'like_color' => $this->likeColor($is_like),

            // 是否可以编辑
            'edit_can' => false,
        ];

        $audit_status = $model_article->audit_status;
        if ($is_self && ($this->isAuditWait($audit_status) || $this->isAuditFail($audit_status))) {
            $audit_status_reason = $this->isAuditFail($audit_status)
                ? "，驳回理由：{$model_article->audit_reason}"
                : '';
            $edit_can = $this->isAuditFail($audit_status);
            $data_audit = [
                // 增加审核状态的返回
                'audit_status_text' => ZsMemberArticle::auditStatusRelsMini()[$audit_status] ?? '',
                'audit_status_class' => ZsMemberArticle::auditStatusClassRelsMini()[$audit_status] ?? '',
                'audit_status_reason' => $audit_status_reason,

                // 是否可以编辑
                'edit_can' => $edit_can,
            ];
            $data = array_merge($data, $data_audit);
        }

        $list = [];
        if ($this->isAuditPass($audit_status)) {
            $list = $this->relateList($article_id, $vipcode);
        }
        return jsonData(1, '成功', compact('data', 'list'));
    }

    /**
     * 发布种草页的详情数据
     */
    public function publishdetail()
    {
        $article_id = Request::param('article_id');
        $vipcode = Request::param('vipcode');

        $model_article = $this->getArticle($article_id);

        $list_media = $this->listFirstMediaItem($model_article->media_arr);
        $media_list = $this->findMediaList($list_media, $model_article->media_arr)
            ->map(function ($item) {
                return [
                    'media_id' => $item->id,
                    'url' => $item->url,
                ];
            });

        $data = [
            'article_id' => $model_article->id,
            'title' => $model_article->title,
            'content' => $model_article->content,
            'media_list' => $media_list,
            'media_arr' => $model_article->media_arr,
            'rel_topic_id' => $model_article->rel_topic_id,
            'rel_topic_text' => $model_article->relTopic->name ?? '',
            'rel_store_id' => $model_article->rel_business_id,
            'rel_store_text' => $model_article->relBusiness->brandname ?? '',
            'rel_coupon_id' => $model_article->rel_coupon_tid,
            'rel_coupon_text' => $model_article->relCoupon->tname ?? '',
        ];
        return jsonData(1, '成功', compact('data'));
    }

    /**
     * 收到的赞列表
     */
    public function receivelike()
    {
        $vipcode = Request::param('vipcode');
        $list_like = ZsMemberLike::where('article_vipcode', $vipcode)
            ->where('like_status', ZsMemberLike::LIKE_STATUS_ON)
            ->with('memberUser')
            ->select();

        $list = $list_like->map(function ($item_like) {
            $create_time = $item_like->create_at;
            $time = strtotime($create_time);

            $default_nickname = '神秘用户';
            $default_avatar = '/static/images/face.png';
            $user_nickname = $item_like->memberUser->nickName ?? '';
            $user_avatar = $item_like->memberUser->avatarUrl ?? '';
            $user_nickname = mb_substr($user_nickname ?: $default_nickname, 0, 8, 'utf-8');
            $user_avatar = $user_avatar ?: $default_avatar;
            return [
                'user_nickname' => $user_nickname,
                'user_avatar' => $user_avatar,
                'create_date' => date('Y年m月d日', $time),
                'create_time' => $create_time,
            ];
        });

        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 话题列表
     */
    public function topiclist()
    {
        $list_topic = ZsMemberTopic::where('status', ZsMemberTopic::STATUS_ON)
            ->order('id', 'desc')
            ->select();

        $list = $list_topic->map(function ($item_topic) {
            return [
                'id' => $item_topic->id,
                'name' => $item_topic->name,
            ];
        });
        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 商户列表
     */
    public function storelist()
    {
        $name = Request::param('name');
        $list_business = ZsBusiness::where('status', ZsBusiness::STATUS_ON)
            ->whereLike('brandname', "%{$name}%")
            ->order('id', 'asc')
            ->select();

        $list = $list_business->map(function ($item_business) {
            return [
                'id' => $item_business->id,
                'name' => $item_business->brandname,
            ];
        });
        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 已领取优惠券列表
     */
    public function couponlist()
    {
        // $vipcode = Request::param('vipcode');
        // $list_tid = ZsMemberCouponProvide::where('uid', $vipcode)
        //     ->field('tid')
        //     ->distinct(true)
        //     ->order('id', 'desc')
        //     ->column('tid');

        // $list_coupon = ZsMemberCoupon::whereIn('tid', $list_tid)
        //     ->order('id', 'desc')
        //     ->select();
        $bid = Request::param('bid');
        $list_coupon = ZsMemberCoupon::where('bid', $bid)
            ->where('status', 2)
            ->where('receive_status', 0)
            ->whereTime('end_time', '>', date('Y-m-d H:i:s'))
            ->order('id', 'asc')
            ->select();

        $list = $list_coupon->map(function ($item_coupon) {
            return [
                'id' => $item_coupon->tid,
                'name' => $item_coupon->tname,
            ];
        });
        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 提交种草内容
     */
    public function submit()
    {
        $vipcode = Request::param('vipcode');
        $article_id = Request::param('article_id');
        $media_arr = Request::param('media_arr');
        $title = Request::param('title') ?: '';
        $content = Request::param('content') ?: '';
        $rel_topic_id = Request::param('rel_topic_id') ?: 0;
        $rel_business_id = Request::param('rel_business_id') ?: 0;
        $rel_coupon_tid = Request::param('rel_coupon_tid') ?: '';
        $media_arr = (array) $media_arr;

        if (empty($title)) {
            return jsonData(0, '标题不能为空');
        }
        if (empty(count($media_arr))) {
            return jsonData(0, '上传图片不能为空');
        }
        if (!$this->wxMsgSecCheck($title)) {
            return jsonData(0, '标题不合规，请修改!');
        }
        if ($content && !$this->wxMsgSecCheck($content)) {
            return jsonData(0, '内容不合规，请修改!');
        }

        $now = date('Y-m-d H:i:s');
        $model_article = new ZsMemberArticle();
        if ($article_id) {
            $model_article = $this->getArticle($article_id);
            if (!$model_article) {
                return jsonData(0, '种草内容不存在');
            }
            if ($model_article->vipcode !== $vipcode) {
                return jsonData(0, '这不是你的种草，禁止修改');
            }
            if (!$this->isAuditFail($model_article->audit_status)) {
                return jsonData(0, '当前不是审核驳回状态，禁止修改');
            }
        }
        $model_article->vipcode = $vipcode;
        $model_article->title = $title;
        $model_article->content = $content;
        $model_article->rel_topic_id = $rel_topic_id;
        $model_article->rel_business_id = $rel_business_id;
        $model_article->rel_coupon_tid = $rel_coupon_tid;
        $model_article->media_arr = array_values($media_arr);
        $model_article->audit_status = ZsMemberArticle::AUDIT_STATUS_WAIT;
        $model_article->submit_at = $now;
        $model_article->save();

        $is_reward = $this->businessIsReward($rel_business_id);
        $msg_plain = '审核通过后将展示在种草活动页，请耐心等待';
        $msg_reward = '发布奖励将在审核通过后的30分钟内发放';
        return jsonData(1, $is_reward ? $msg_reward : $msg_plain);
    }

    /**
     * 点赞
     */
    public function like()
    {
        $vipcode = Request::param('vipcode');
        $article_id = Request::param('article_id');

        $model_article = $this->getArticle($article_id);
        if (!$model_article) {
            return jsonData(0, '种草内容不存在');
        }
        if ($model_article->vipcode === $vipcode) {
            return jsonData(0, '不能给自己点赞');
        }

        $model_like = $this->getLikeOne($article_id, $vipcode);
        if (!$model_like) {
            $model_like = new ZsMemberLike();
            $model_like->vipcode = $vipcode;
            $model_like->article_id = $article_id;
            $model_like->article_vipcode = $model_article->vipcode;
        }
        $model_like->like_status = ZsMemberLike::LIKE_STATUS_ON;
        $model_like->save();

        // 更新文章点赞数
        $model_update_article = $this->updateLikeNum($article_id);

        $like_data = [
            'is_like' => true,
            'like_color' => $this->likeColor(true),
            'like_num' => $model_update_article->like_num,
        ];
        return jsonData(1, '已点赞', compact('like_data'));
    }

    /**
     * 取消占赞
     */
    public function unlike()
    {
        $vipcode = Request::param('vipcode');
        $article_id = Request::param('article_id');

        $model_article = $this->getArticle($article_id);
        if (!$model_article) {
            return jsonData(0, '种草内容不存在');
        }
        if ($model_article->vipcode === $vipcode) {
            return jsonData(0, '不能给自己点赞');
        }

        $model_like = $this->getLikeOne($article_id, $vipcode);
        if (!$model_like) {
            return jsonData(0, '非法操作');
        }
        $model_like->like_status = ZsMemberLike::LIKE_STATUS_OFF;
        $model_like->save();

        // 更新文章点赞数
        $model_update_article = $this->updateLikeNum($article_id);

        $like_data = [
            'is_like' => false,
            'like_color' => $this->likeColor(false),
            'like_num' => $model_update_article->like_num,
        ];
        return jsonData(1, '已取消', compact('like_data'));
    }

    /**
     * 获取推广图片
     */
    public function promoImage()
    {
        $promo_data = sysdata('minigrass');
        return jsonData(1, '成功', compact('promo_data'));
    }

    /**
     * 获取用户信息
     */
    public function findMember()
    {
        $vipcode = Request::param('vipcode');
        $model_member = $this->getMemberMeal($vipcode);
        if (!$model_member) {
            $member_data = [
                'show_update_info_btn' => false,
                // 是否显示[发布种草]按钮（冗余字段）
                'publish_can' => true,
            ];
            return jsonData(1, '成功', compact('member_data'));
        }

        // 是否显示更新资料按钮
        $show_update_info_btn = $this->showUpdateInfoBtn($model_member->nickName);

        $default_nickname = '神秘用户';
        $default_avatar = '/static/images/face.png';
        $user_nickname = $model_member->nickName ?: $default_nickname;
        $user_avatar = $model_member->avatarUrl ?: $default_avatar;

        $member_data = [
            'vipcode' => $model_member->vipcode,
            'user_nickname' => $user_nickname,
            'user_avatar' => $user_avatar,
            'show_update_info_btn' => $show_update_info_btn,
            // 是否显示[发布种草]按钮（冗余字段）
            'publish_can' => true,
        ];
        return jsonData(1, '成功', compact('member_data'));
    }

    /**
     * 更新用户信息
     */
    public function upMember()
    {
        $vipcode = Request::param('vipcode');
        $nickName = Request::param('nickName');
        $avatarUrl = Request::param('avatarUrl');
        $country = Request::param('country');
        $province = Request::param('province');
        $city = Request::param('city');
        $gender = Request::param('gender');
        // Log::debug('function upMember ==>' . json_encode(compact(
        //     'vipcode',
        //     'nickName',
        //     'avatarUrl',
        //     'country',
        //     'province',
        //     'city',
        //     'gender'
        // ), JSON_UNESCAPED_UNICODE));

        $model_member = $this->getMemberMeal($vipcode);
        $model_member->nickName = $nickName;
        $model_member->avatarUrl = $avatarUrl;
        $model_member->country = $country;
        $model_member->province = $province;
        $model_member->city = $city;
        $model_member->gender = $gender;
        $model_member->save();

        // 是否显示更新资料按钮
        $show_update_info_btn = $this->showUpdateInfoBtn($model_member->nickName);

        $default_nickname = '神秘用户';
        $default_avatar = '/static/images/face.png';
        $user_nickname = $model_member->nickName ?: $default_nickname;
        $user_avatar = $model_member->avatarUrl ?: $default_avatar;

        $member_data = [
            'vipcode' => $model_member->vipcode,
            'user_nickname' => $user_nickname,
            'user_avatar' => $user_avatar,
            'show_update_info_btn' => $show_update_info_btn,
            // 是否显示[发布种草]按钮（冗余字段）
            'publish_can' => true,
        ];
        return jsonData(1, '成功', compact('member_data'));
    }

    /**
     * 种草评论提交
     */
    public function sendComment()
    {
        $article_id = Request::param('article_id');
        $vipcode = Request::param('vipcode');
        $reply_comment_id = Request::param('reply_comment_id') ?: 0;
        $content = Request::param('content');
        $content = trim($content);

        if (empty($content)) {
            return jsonData(0, '请填写评论内容');
        }

        if (empty($vipcode)) {
            return jsonData(0, '请先登录');
        }

        $res_check = $this->wxMsgSecCheck($content);
        if (!$res_check) {
            return jsonData(0, '评论不合规，请修改!');
        }

        $model_article = $this->getArticle($article_id);
        if (!$model_article) {
            return jsonData(0, '种草不存在');
        }

        $reply_vipcode = '';
        $depth = 0;
        if ($reply_comment_id) {
            $model_comment_parent = $this->getComment($reply_comment_id);
            if (!$model_comment_parent) {
                return jsonData(0, '回复评论失败');
            }
            $reply_vipcode = $model_comment_parent->vipcode;
            $depth = $model_comment_parent->depth + 1;
        }

        $now = date('Y-m-d H:i:s');

        $model_comment = new ZsMemberArticleComment();
        $model_comment->vipcode = $vipcode;
        $model_comment->reply_comment_id = $reply_comment_id;
        $model_comment->reply_vipcode = $reply_vipcode;
        $model_comment->depth = $depth;
        $model_comment->article_id = $article_id;
        $model_comment->article_vipcode = $model_article->vipcode;
        $model_comment->content = $content;
        $model_comment->audit_status = ZsMemberArticleComment::AUDIT_STATUS_WAIT;
        $model_comment->submit_at = $now;
        $model_comment->save();

        $list = $this->returnListComment($article_id, $vipcode);
        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 种草评论提交
     */
    public function editComment()
    {
        $comment_id = Request::param('comment_id');
        $vipcode = Request::param('vipcode');
        $content = Request::param('content');
        $content = trim($content);

        if (empty($content)) {
            return jsonData(0, '请填写评论内容');
        }

        if (empty($vipcode)) {
            return jsonData(0, '请先登录');
        }

        $model_comment = $this->getArticleComment($comment_id);
        if (!$model_comment) {
            return jsonData(0, '评论不存在');
        }

        if ($model_comment->vipcode !== $vipcode) {
            return jsonData(0, '编辑评论失败');
        }

        $res_check = $this->wxMsgSecCheck($content);
        if (!$res_check) {
            return jsonData(0, '评论不合规，请修改!');
        }

        $now = date('Y-m-d H:i:s');

        $model_comment->content = $content;
        $model_comment->audit_status = ZsMemberArticleComment::AUDIT_STATUS_WAIT;
        $model_comment->submit_at = $now;
        $model_comment->save();

        $list = $this->returnListComment($model_comment->article_id, $vipcode);
        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 种草首页-话题列表
     */
    public function topicall()
    {
        $list_topic = ZsMemberTopic::where('status', ZsMemberTopic::STATUS_ON)
            ->order('id', 'desc')
            ->select();

        $list = $list_topic->map(function ($item_topic) {
            return [
                'id' => $item_topic->id,
                'name' => '#'.$item_topic->name.'#',
            ];
        });
        $list->unshift(['id' => 0, 'name' => '#全部话题#']);
        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 我的种草-收到的赞和金币数
     */
    public function myindexinfo()
    {
        $vipcode = Request::param('vipcode');

        $receive_like_num = ZsMemberLike::where('article_vipcode', $vipcode)
            ->where('like_status', ZsMemberLike::LIKE_STATUS_ON)
            ->count();
        $gold_num = $this->getGoldAll($vipcode);
        return jsonData(1, '成功', compact('receive_like_num', 'gold_num'));
    }

    /**
     * 根据 id 查询评论记录
     */
    private function getComment($id)
    {
        return ZsMemberArticleComment::find($id);
    }

    /**
     * 获取种草评论
     */
    public function listComment()
    {
        $vipcode = Request::param('vipcode');
        $article_id = Request::param('article_id');
        $type = Request::param('type');

        $list = $this->returnListComment($article_id, $vipcode, $type);
        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 获取总金币
     */
    private function getGoldAll($vipcode)
    {
        return ZsRewardLog::where('vipcode', $vipcode)->sum('gold');
    }

    private function returnListComment($article_id, $vipcode, $type = 'simple')
    {
        $is_simple = $type !== 'all';

        $list_comment = ZsMemberArticleComment::where('article_id', $article_id)
            ->where(function ($query) use ($vipcode) {
                $query->whereIn('audit_status', [
                    // ZsMemberArticleComment::AUDIT_STATUS_WAIT,
                    ZsMemberArticleComment::AUDIT_STATUS_PASS,
                ]);
                if ($vipcode) {
                    $query->whereOr('vipcode', $vipcode);
                }
            })
            ->where('status', ZsMemberArticleComment::STATUS_ON)
            ->with('memberUser', 'replyMemberUser')
            ->order('id', 'asc')
            ->select();

        $list = $list_comment->map(function ($item_comment) use ($vipcode) {
            $default_nickname = '神秘用户';
            $default_avatar = '/static/images/face.png';
            $user_nickname = $item_comment->memberUser->nickName ?? '';
            $user_avatar = $item_comment->memberUser->avatarUrl ?? '';
            $user_nickname = $user_nickname ?: $default_nickname;
            $user_avatar = $user_avatar ?: $default_avatar;

            $is_reply = boolval($item_comment->reply_comment_id);
            $reply_user_nickname = $item_comment->replyMemberUser->nickName ?? '';
            $reply_user_nickname = $reply_user_nickname ?: $default_nickname;

            $audit_status = $item_comment->audit_status;
            $reply_can = $this->isAuditPassComment($audit_status);

            $audit_status_text =
            $audit_status_class =
            $audit_status_reason = '';
            $edit_can = false;
            if ($vipcode && $item_comment->vipcode === $vipcode) {
                $audit_status_text = ZsMemberArticleComment::auditStatusRelsMini()[$audit_status] ?? '';
                $audit_status_class = ZsMemberArticleComment::auditStatusClassRelsMini()[$audit_status] ?? '';
                $audit_status_reason = $this->isAuditFailComment($audit_status)
                    ? "，驳回理由：{$item_comment->audit_reason}"
                    : '';
                $edit_can = $this->isAuditFailComment($audit_status);
            }
            return [
                'comment_id' => $item_comment->id,
                'content' => $item_comment->content,
                'user_nickname' => $user_nickname,
                'user_avatar' => $user_avatar,
                'date' => substr($item_comment->create_at, 0, -3),
                'is_reply' => $is_reply,
                'reply_user_nickname' => $is_reply ? "@{$reply_user_nickname}" : '',
                'reply_can' => $reply_can,

                'audit_status_text' => $audit_status_text,
                'audit_status_class' => $audit_status_class,
                'audit_status_reason' => $audit_status_reason,
                'edit_can' => $edit_can,
            ];
        });
        return $list;
    }

    /**
     * 是否显示[更新资料]按钮（昵称为空则显示）
     */
    private function showUpdateInfoBtn($nickName)
    {
        return !$nickName;
    }

    /**
     * 根据vipcode获取会员记录
     */
    private function getMemberMeal($vipcode)
    {
        return ZsMemberMeal::where('vipcode', $vipcode)->find();
    }

    /**
     * 获取文章记录
     */
    private function getArticle($article_id)
    {
        return ZsMemberArticle::with('memberUser', 'relTopic', 'relCoupon')
            ->find($article_id);
    }

    /**
     * 根据id查找种草评论记录
     */
    private function getArticleComment($id)
    {
        $model_comment = new ZsMemberArticleComment();
        $model = $model_comment->find($id);
        return $model;
    }

    /**
     * 根据文章ID和会员标识获取文章点赞记录
     */
    private function getLikeOne($article_id, $vipcode)
    {
        return ZsMemberLike::where('article_id', $article_id)
            ->where('vipcode', $vipcode)
            ->find();
    }

    /**
     * 计算文章点赞数
     */
    private function calcLikeNum($article_id)
    {
        return ZsMemberLike::where('article_id', $article_id)
            ->where('like_status', ZsMemberLike::LIKE_STATUS_ON)
            ->count();
    }

    /**
     * 更新文章点赞数
     */
    private function updateLikeNum($article_id)
    {
        $like_num = $this->calcLikeNum($article_id);
        $model_article = $this->getArticle($article_id);
        if (!$model_article) {
            return false;
        }

        $model_article->like_num = $like_num;
        $model_article->save();
        return $model_article;
    }

    /**
     * 根据图片 ID 获取图片列表
     */
    private function listFirstMediaItem(array $list_first_media)
    {
        return ZsMemberMedia::whereIn('id', $list_first_media)->select();
    }

    /**
     * 获取第一张图列表
     */
    private function listFirstMedia(array $list_media)
    {
        $list = [];
        foreach ($list_media as $item_media) {
            $list[] = $this->firstMedia($item_media);
        }
        return $list;
    }

    /**
     * 获取第一张图
     */
    private function firstMedia($item_media)
    {
        $item_arr = is_array($item_media)
            ? $item_media
            : json_decode($item_media, true);
        return $item_arr[0] ?? '';
    }

    /**
     * 是否审核驳回状态
     */
    private function isAuditFail($audit_status)
    {
        return $audit_status === ZsMemberArticle::AUDIT_STATUS_FAIL;
    }

    /**
     * 是否待审核状态
     */
    private function isAuditWait($audit_status)
    {
        return $audit_status === ZsMemberArticle::AUDIT_STATUS_WAIT;
    }

    /**
     * 是否审核通过状态
     */
    private function isAuditPass($audit_status)
    {
        return $audit_status === ZsMemberArticle::AUDIT_STATUS_PASS;
    }

    /**
     * 是否审核驳回状态-评论
     */
    private function isAuditFailComment($audit_status)
    {
        return $audit_status === ZsMemberArticleComment::AUDIT_STATUS_FAIL;
    }

    /**
     * 是否审核通过状态-评论
     */
    private function isAuditPassComment($audit_status)
    {
        return $audit_status === ZsMemberArticleComment::AUDIT_STATUS_PASS;
    }

    /**
     * 文章 status 是否正常状态
     */
    private function isArticleStatusOn($status)
    {
        return $status === ZsMemberArticle::STATUS_ON;
    }

    /**
     * 根据文章ID数组和会员标识返回会员已点赞的文章ID数组
     *
     * @param array 文章ID数组
     * @param string 会员标识
     * @return array
     */
    private function ilkeArticleIdArr($article_id_arr, $vipcode)
    {
        $list_like = ZsMemberLike::where('vipcode', $vipcode)
            ->whereIn('article_id', $article_id_arr)
            ->select();
        $list = $list_like->where('like_status', ZsMemberLike::LIKE_STATUS_ON)->column('article_id');
        return $list;
    }

    /**
     * 点赞按钮的颜色
     */
    private function likeColor($is_like)
    {
        return $is_like ? '#ff7171' : '#909399';
    }

    private function findMediaList($list_media, $media_arr)
    {
        $media_arr = is_array($media_arr)
            ? $media_arr
            : json_decode($media_arr, true);

        $list = collect($media_arr)->map(function ($media_id) use ($list_media) {
            $media_item = $list_media->where('id', $media_id)->first();
            return $media_item;
        })
            ->filter(function ($item) {
                return $item->url;
            })
            ->values();
        return $list;
    }

    /**
     * 拼接给 u-swiper 组件使用的数组
     */
    private function joinSwiper($list_media, $media_arr)
    {
        $media_arr = is_array($media_arr)
            ? $media_arr
            : json_decode($media_arr, true);

        $list = collect($media_arr)->map(function ($media_id) use ($list_media) {
            $media_item = $list_media->where('id', $media_id)->first();
            return [
                'image' => $media_item->url ?? '',
            ];
        })
            ->filter(function ($item) {
                return $item['image'];
            })
            ->all();
        // $list = $list_media->map(function ($item_media) {
        //     return [
        //         'image' => $item_media->url,
        //     ];
        // })
        //     ->all();
        return $list;
    }

    /**
     * 种草详情页的关联种草数据
     */
    private function relateList($article_id, $vipcode)
    {
        $base = ZsMemberArticle::where('audit_status', ZsMemberArticle::AUDIT_STATUS_PASS)
            ->where('status', ZsMemberArticle::STATUS_ON);

        $count = (clone $base)->count();
        $limit = 14;
        $offset = mt_rand(0, max(0, $count - $limit));

        $list_article = (clone $base)->limit($offset, $limit)->select();
        $list_article_filter = $list_article->filter(function ($item) use ($article_id, $vipcode) {
            // 过滤掉当前种草和当前用户所发布的种草
            return $item->id != $article_id && $item->vipcode != $vipcode;
        })
            ->shuffle()
            ->slice(0, 2);

        $list_media = $list_article_filter->column('media_arr');
        $list_first_media = $this->listFirstMedia($list_media);
        $list_first_media_item = $this->listFirstMediaItem($list_first_media);

        $list = $list_article_filter->map(function ($item_article) use ($list_first_media_item) {
            $first_media_id = $this->firstMedia($item_article->media_arr);
            $first_media_item = $list_first_media_item->where('id', $first_media_id)->first();

            $default_nickname = '神秘用户';
            $default_avatar = '/static/images/face.png';
            $user_nickname = $item_article->memberUser->nickName ?? '';
            $user_avatar = $item_article->memberUser->avatarUrl ?? '';
            $user_nickname = mb_substr($user_nickname ?: $default_nickname, 0, 8, 'utf-8');
            $user_avatar = $user_avatar ?: $default_avatar;
            return [
                'article_id' => $item_article->id,
                'title' => $item_article->title,
                'user_nickname' => $user_nickname,
                'user_avatar' => $user_avatar,
                'like_num' =>$item_article->like_num,
                'headimg' => $first_media_item['url'] ?? '',

                'is_like' => false,
                'like_color' => $this->likeColor(false),
            ];
        });

        return $list;
    }

    /**
     * 话题文字前后加#
     */
    private function joinTopicText($text) {
        return "#{$text}#";
    }

    /**
     * 根据商户ID判断商户是否有发布奖励
     */
    private function businessIsReward($business_id)
    {
        return boolval($business_id);
    }

    /**
     * 调用微信接口进行内容敏感检测
     */
    private function wxMsgSecCheck($content)
    {
        try {
            Security::instance($this->config)->msgSecCheck($content);
        } catch (InvalidResponseException $e) {
            if ($e->getCode() === 87014) {
                return false;
            }
        }
        return true;
    }

    /**
     * 默认图片
     * （存在用户未上传图片提交成功的情况，避免报错，返回默认图片）
     */
    private function defaultPic()
    {
        return '';
    }
}
